# -*- coding:UTF-8 -*-
from elasticsearch import Elasticsearch

class ConnES:
    def __init__(self, host, port, index):
        self.host = host
        self.port = int(port)
        self.index = index

        self._conn = self.connES()

    #连接
    def connES(self):
        conn = False
        try:
            conn = Elasticsearch([{'host': self.host,'port': self.port}])
        except Exception,data:
            conn = False
        return conn

    #查找
    def find(self, estype, param, value):
        res = False
        if(self._conn):
            query_json = {"match": { param: value } }
            try:
                res = self._conn.search(index= self.index, doc_type = estype, body={"query": query_json} )['hits']['hits']
            except Exception,data:
                res = False
        return res

    # 通过查询然后删除
    def delete(self, estype, param, value):
        flag = False
        if(self._conn):
            try:
                query_json = {"match": {param: value}}
                flag = self._conn.delete_by_query(index=self.index, doc_type = estype , body={"query": query_json} )
            except Exception,data:
                flag = False
        return flag